package com.circle.model.module;

import com.alibaba.fastjson.JSON;
import com.circle.model.entity.AjaxJson;
import com.circle.model.util.OkHttpFactory;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class OkPost {
    private String url;
    private Map<String, String> headers;
    private Map<String, String> params;
    private RequestBody requestBody;
    private OkHttpClient client;
    private Request.Builder requestBuilder;
    private MediaType mediaType;
    private Map<String, String> cookies;

    public OkPost(String url) {
        this.url = url;
        this.headers = new HashMap<>();
        this.params = new HashMap<>();
        this.cookies = new HashMap<>();
        this.client = OkHttpFactory.getClient();
        this.requestBuilder = new Request.Builder();
        this.mediaType = MediaType.parse("application/json; charset=utf-8");
    }

    /**
     * 设置Content-Type
     */
    public OkPost setMediaType(String mediaType) {
        this.mediaType = MediaType.parse(mediaType);
        return this;
    }

    /**
     * 添加单个请求头
     */
    public OkPost addHeader(String key, String value) {
        this.headers.put(key, value);
        return this;
    }

    /**
     * 添加多个请求头
     */
    public OkPost addHeaders(Map<String, String> headers) {
        if (headers != null) {
            this.headers.putAll(headers);
        }
        return this;
    }

    /**
     * 添加表单参数
     */
    public OkPost addFormParam(String key, String value) {
        this.params.put(key, value);
        return this;
    }

    /**
     * 添加多个表单参数
     */
    public OkPost addFormParams(Map<String, String> params) {
        if (params != null) {
            this.params.putAll(params);
        }
        return this;
    }

    /**
     * 设置JSON请求体
     */
    public OkPost setJsonBody(String json) {
        this.requestBody = RequestBody.create(mediaType, json);
        return this;
    }

    /**
     * 设置文本请求体
     */
    public OkPost setStringBody(String content) {
        this.mediaType = MediaType.parse("text/plain; charset=utf-8");
        this.requestBody = RequestBody.create(mediaType, content);
        return this;
    }

    /**
     * 设置文件请求体
     */
    public OkPost setFileBody(File file) {
        this.mediaType = MediaType.parse("application/octet-stream");
        this.requestBody = RequestBody.create(mediaType, file);
        return this;
    }

    /**
     * 构建表单请求体
     */
    private RequestBody buildFormBody() {
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            formBuilder.add(entry.getKey(), entry.getValue());
        }
        return formBuilder.build();
    }

    /**
     * 构建Multipart请求体
     */
    public OkPost addMultipartFile(String name, File file) {
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        
        // 添加文件
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        multipartBuilder.addFormDataPart(name, file.getName(), fileBody);
        
        // 添加其他表单参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue());
        }
        
        this.requestBody = multipartBuilder.build();
        return this;
    }

    /**
     * 添加单个Cookie
     */
    public OkPost addCookie(String name, String value) {
        this.cookies.put(name, value);
        return this;
    }

    /**
     * 添加多个Cookie
     */
    public OkPost addCookies(Map<String, String> cookies) {
        if (cookies != null) {
            this.cookies.putAll(cookies);
        }
        return this;
    }

    /**
     * 构建请求对象
     */
    private Request buildRequest() {
        // 设置URL
        requestBuilder.url(url);

        // 添加请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            requestBuilder.addHeader(entry.getKey(), entry.getValue());
        }

        // 处理Cookie
        if (!cookies.isEmpty()) {
            StringBuilder cookieString = new StringBuilder();
            for (Map.Entry<String, String> cookie : cookies.entrySet()) {
                if (cookieString.length() > 0) {
                    cookieString.append("; ");
                }
                cookieString.append(cookie.getKey()).append("=").append(cookie.getValue());
            }
            requestBuilder.addHeader("Cookie", cookieString.toString());
        }

        // 设置请求体
        if (requestBody == null) {
            requestBody = buildFormBody();
        }

        // 设置POST方法
        requestBuilder.post(requestBody);

        return requestBuilder.build();
    }

    /**
     * 同步执行POST请求
     */
    public AjaxJson execute() throws IOException {
        Request request = buildRequest();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response);
            }
            String msg = response.body() != null ? response.body().string() : "";
            return JSON.parseObject(msg, AjaxJson.class);
        }
    }

    /**
     * 异步执行POST请求
     */
    public void enqueue(Callback callback) {
        Request request = buildRequest();
        client.newCall(request).enqueue(callback);
    }
}
